#! /usr/bin/env bash
#
# Install tree-sitter's runtime library and inject ocaml-tree-sitter's
# runtime code to be built with semgrep-core.
#
set -eu

# Temporary block to help with transition (2021-04-29):
# ocaml-tree-sitter used to be a submodule, and if it's still there,
# we need to delete it and start fresh.
#
if [[ -d ocaml-tree-sitter ]]; then
  # test if ocaml-tree-sitter is a submodule
  if [[ -n "$(git -C ocaml-tree-sitter rev-parse --show-superproject-working-tree)" ]];
  then
    echo "Removing left-over submodule 'ocaml-tree-sitter'.".
    rm -rf ocaml-tree-sitter

    echo "Attempting to remove any opam-installed ocaml-tree-sitter."
    opam remove tree-sitter
    echo "Attempting to remove any ocamlfind-installed ocaml-tree-sitter."
    ocamlfind remove tree-sitter
  fi
fi

# We don't plug in this repo as a submodule because itself contains over
# 600 MB of submodules (tree-sitter-* repos) which are not needed
# to build semgrep-core.
#
if [[ ! -d ocaml-tree-sitter ]]; then
  git clone https://github.com/returntocorp/ocaml-tree-sitter.git
else
  echo "Found local copy of ocaml-tree-sitter."
fi

(
  cd ocaml-tree-sitter
  git fetch -p origin

  # The current version of ocaml-tree-sitter being used.
  #
  # In general, there's no need to change this when a tree-sitter parser is
  # updated or created. In theory, this needs only change when the scripts
  # below change or when the runtime library changes (src/run, src/bindings).
  # If unsure, just update to the latest commit on the main branch.
  #
  git checkout 2263f3f

  # Install the C library. OCaml sources are built as part of the semgrep-core
  # dune project. See the symlinks in semgrep-core/src/ocaml-tree-sitter.
  ./scripts/install-tree-sitter-lib
)

# Plug OCaml sources into the semgrep-core dune project
symlink=semgrep-core/src/ocaml-tree-sitter/src
if [[ ! -e "$symlink" ]]; then
  ln -s ../../../ocaml-tree-sitter/src "$symlink"
fi

symlink=semgrep-core/tree-sitter.opam
if [[ ! -e "$symlink" ]]; then
  ln -s ../ocaml-tree-sitter/tree-sitter.opam "$symlink"
fi
